package com.woniu.shops.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import com.woniu.common.vo.AjaxResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/captcha")
@CrossOrigin
public class CaptchaController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @RequestMapping("/getVerifyCodeImage")
    public AjaxResult getVerifyCodeImage(HttpServletResponse response) throws IOException {
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
// 重新生成code
        lineCaptcha.createCode();
        String code = lineCaptcha.getCode();

        System.out.println(code);

        String uuid = IdUtil.randomUUID().toUpperCase().replace("_","");
        //将图片中验证码的内容存入到redis中  以uuid 作为key
        redisTemplate.opsForValue().set(uuid,code);

        //存储图片的地址
        String imageBase64Data = lineCaptcha.getImageBase64Data();
        AjaxResult ajaxResult = AjaxResult.success("生成成功",imageBase64Data);
        ajaxResult.put("uuid",uuid);
        return ajaxResult;
    }



}

